import { reactive, toRefs, onMounted } from 'vue';

interface IParams {
  pageNum?: number;
  pageSize?: number;
  [key: string]: any;
}
interface IOptions {
  extraParams?: object; // 固定参数
  transformParam?: Function; //暂不使用
  transformResult?: Function; //暂不使用
}

export function useTableFetch(
  service: Function,
  showLog = false,
  options: IOptions = {}
) {
  const { extraParams } = options;
  const result = reactive({
    data: [],
    currentPage: 1,
    pageSize: 10,
    total: 0,
    loading: false,
    params: {}
  });

  async function run(p: IParams = {}) {
    const { pageNum = 1, pageSize = 10, ...rest } = p;
    // 依据后端进行入参处理transformParam
    const finallyParams = {
      pageNum,
      pageSize,
      ...rest,
      ...extraParams
    };
    result.params = finallyParams;
    result.loading = true;
    if (showLog) {
      console.log('当前执行参数--', finallyParams);
    }
    try {
      const response = await service(finallyParams);
      result.loading = false;
      // transformResult处理
      const {
        code,
        data: { total, list }
      } = response;
      if (code === 200) {
        result.currentPage = pageNum;
        result.pageSize = pageSize;
        result.total = total * 1;
        result.data = list;
      } else {
        result.currentPage = 1;
        result.pageSize = 10;
        result.total = 0;
        result.data = [];
      }
    } catch (err) {
      result.loading = false;
      result.currentPage = 1;
      result.pageSize = 10;
      result.total = 0;
      result.data = [];
    }
  }

  function refresh(isGoFirst = false) {
    if (isGoFirst) {
      run({
        ...result.params,
        pageNum: 1
      });
    } else {
      run(result.params);
    }
  }

  return {
    ...toRefs(result),
    run,
    refresh
  };
}

interface IResourceOption {
  params?: object;
  defaultData?: any;
  formatResult?: Function;
}
export function useResource(service: Function, options: IResourceOption = {}) {
  const { params, defaultData, formatResult } = options;
  const result = reactive({
    data: defaultData,
    loading: false
  });
  async function search() {
    result.loading = true;
    try {
      const response = await service(params);
      result.loading = false;
      const { success, data } = response;
      if (success) {
        result.data = formatResult
          ? formatResult(data || defaultData)
          : data || defaultData;
      }
    } catch (err) {
      result.loading = false;
      result.data = defaultData;
    }
  }

  onMounted(() => search());
  return {
    ...toRefs(result)
  };
}

export enum FieldType {
  'INTEGER' = 'icon-metricsx-intleixing',
  'STRING' = 'icon-metricsx-stringleixing',
  'DATETIME' = 'icon-metricsx-a-rilicalender',
  'BOOLEAN' = 'icon-metricsx-Booleanbuerleixing',
  'DECIMAL' = 'icon-metricsx-floatleixing'
}

export enum bindType {
  'DIMENSION' = 'DIMENSION',
  'METRICS' = 'METRICS',
  'TIMEPERIOD' = 'TIMEPERIOD'
}
